package org.ns.summer.mvc.fuzzysearch;

import java.util.HashMap;
import java.util.Map;

public class SearchNode {

    private char c; // 一个字符 如果是 * 则是全匹配

    private Map<Character, SearchNode> nexts = new HashMap<>();

    private Object value; // 匹配到结果值，值为不为null则匹配成功

    private SearchNode prev;

    public SearchNode(char c) {
        this.c = c;
    }

    public SearchNode getNextOrCreate(char c) {
        SearchNode nextNode = nexts.get(c);
        if (nextNode == null) {
            nextNode = new SearchNode(c);
            nextNode.prev = this;
            nexts.put(c, nextNode);
        }
        return nextNode;
    }

    public SearchNode getNext(char c) {
        SearchNode searchNode = nexts.get(c);
        if (searchNode == null) {
            searchNode = nexts.get('*');
            if (searchNode == null && isAll()) {
                searchNode = this;
            }
        }
        return searchNode;
    }

    void setValue(Object value) {
        this.value = value;
        if (isAll() && prev != null) {
            prev.setValue(value);
        }
    }

    public Object getValue() {
        return value;
    }

    public char getC() {
        return c;
    }

    public boolean isEnd() {
        return value != null;
    }

    public boolean isAll() {
        return c == '*';
    }


}
